package com.fingard.dsp.bank.directbank.ynrcc01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/5/10.
 */
public class YNRCC01Transaction extends YNRCC01Base implements ITransaction {
    /**
     * 历史明细
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo ="";
        retAtsTrans.writeStart();
        try{
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //跨月查询分月进行查询
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //拼接请求报文:1.1账户明细查询
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                YNRCC01Header header = new YNRCC01Header();
                header.transCode  ="B2EActTrsQry";//交易码
                header.erpJnlNo =p_req7516.reqHeader.transSeqID;//前台流水号
                wirteCommenHeader(xmlTextWriter,header);
                xmlTextWriter.writeStartElement("Body");
                xmlTextWriter.writeStartElement("Map");
                xmlTextWriter.writeElementString("AcNo",p_req7516.actNum);//帐号
                xmlTextWriter.writeElementString("QryOrd","1");//排序方式 1:时间降序 2:时间升序
                xmlTextWriter.writeElementString("DCFlag","0");//借贷标志0：表示全部1：贷 2：借
                xmlTextWriter.writeElementClosed("MinAmt");//最小金额
                xmlTextWriter.writeElementClosed("MaxAmt");//最大金额
                xmlTextWriter.writeElementString("BeginDate",Format.Date10Format.format(tmpCalendarFrom.getTime()));//查询起始日期
                xmlTextWriter.writeElementString("EndDate",Format.Date10Format.format(tmpClndrStepTo.getTime()));//查询终止日期
                xmlTextWriter.writeEndElement();
                xmlTextWriter.writeEndDocument();
                //请求银行
                String[] resutlt = sendToBank(xmlTextWriter.toXmlString());

                //测试
                //WriteBankLogLn("发送至银行的报文："+xmlTextWriter.toXmlString());
                //String[] resutlt=new String[]{"","<?xml version=\"1.0\" encoding=\"utf-16\"?><Message>  <Head>    <ReturnCode>000000</ReturnCode>    <ReturnMsg>    </ReturnMsg>  </Head>  <Body>    <Map>      <JnlDate>20190116</JnlDate>      <JnlTime>15:12:00</JnlTime>      <TransJnlNo>11111111111</TransJnlNo>      <DCFlag>D</DCFlag>\t  <Amount>11.00</Amount>      <Currency>CNY</Currency>      <ChannelId></ChannelId>      <Balance>204427.00</Balance>\t  <TransInfo>测试</TransInfo>      <AcctOrgan></AcctOrgan>      <PayeeAcName>云南对方户</PayeeAcName>      <PayeeAcNo>22222222222222222</PayeeAcNo>\t  <PayeeBankName>云南省农村信用社</PayeeBankName>    </Map>\t<Map>      <JnlDate>20190116</JnlDate>      <JnlTime>15:12:00</JnlTime>      <TransJnlNo>11111111111</TransJnlNo>      <DCFlag>D</DCFlag>\t  <Amount>11.00</Amount>      <Currency>CNY</Currency>      <ChannelId></ChannelId>      <Balance>204427.00</Balance>\t  <TransInfo>测试</TransInfo>      <AcctOrgan></AcctOrgan>      <PayeeAcName>云南对方户</PayeeAcName>      <PayeeAcNo>22222222222222211</PayeeAcNo>\t  <PayeeBankName>云南省农村信用社</PayeeBankName>    </Map>\t<Map>      <JnlDate>20190116</JnlDate>      <JnlTime>15:12:00</JnlTime>      <TransJnlNo>11111111111</TransJnlNo>      <DCFlag>D</DCFlag>\t  <Amount>12.00</Amount>      <Currency>CNY</Currency>      <ChannelId></ChannelId>      <Balance>202427.00</Balance>\t  <TransInfo>测试</TransInfo>      <AcctOrgan></AcctOrgan>      <PayeeAcName>云南对方户</PayeeAcName>      <PayeeAcNo>22222222222222222</PayeeAcNo>\t  <PayeeBankName>云南省农村信用社</PayeeBankName>    </Map>\t<Map>      <JnlDate>20190116</JnlDate>      <JnlTime>15:12:00</JnlTime>      <TransJnlNo>11111111111</TransJnlNo>      <DCFlag>D</DCFlag>\t  <Amount>13.00</Amount>      <Currency>CNY</Currency>      <ChannelId></ChannelId>      <Balance>203427.00</Balance>\t  <TransInfo>测试</TransInfo>      <AcctOrgan></AcctOrgan>      <PayeeAcName>云南对方户</PayeeAcName>      <PayeeAcNo>22222222222222233</PayeeAcNo>\t  <PayeeBankName>云南省农村信用社</PayeeBankName>    </Map>  </Body></Message>\n"};
                //WriteBankLogStep3(resutlt[1]);

                //处理响应报文
                if(resutlt[0].length()==0){
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].trim(),tmpSbMsg);
                    if(tmpBkReader!=null){
                        String respCode = tmpBkReader.getFirstText("/Message/Head/ReturnCode");
                        String respInfo = tmpBkReader.getFirstText("/Message/Head/ReturnMsg");
                        if ("000000".equals(respCode)) {//交易成功
                            while (tmpBkReader.read("/Message/Body/List/Map")){
                                XElement readXElement = tmpBkReader.readedXElement;
                                //String note="";
                                //1.2查询明细详情获取Remark
                                /*XmlTextWriter xmlTextWriter2 = new XmlTextWriter();
                                YNRCC01Header header2 = new YNRCC01Header();
                                header.transCode  ="B2EActTrsDetailQry";//交易码
                                header.erpJnlNo =p_req7516.reqHeader.transSeqID;//前台流水号
                                wirteCommenHeader(xmlTextWriter2,header2);
                                xmlTextWriter2.writeStartElement("Body");
                                xmlTextWriter2.writeStartElement("Map");
                                xmlTextWriter2.writeElementString("JnlDate",DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("JnlDate").trim()));//交易时间
                                xmlTextWriter2.writeElementString("JnlNo",readXElement.getSingleTextNotNull("JnlNo").trim());//银行流水号(主机流水号)
                                xmlTextWriter2.writeElementString("AcctOrgan",readXElement.getSingleTextNotNull("AcctOrgan").trim());//机构码
                                xmlTextWriter2.writeEndElement();
                                xmlTextWriter2.writeEndDocument();
                                String[] resutlt2 = sendToBank(xmlTextWriter2.toXmlString());
                                if(resutlt2[0].length()==0){
                                    StringBuilder tmpSbMsg2 = new StringBuilder();
                                    XmlTextReader tmpBkReader2 = loadBankRespXmlReader(resutlt2[1].trim(),tmpSbMsg2);
                                    if(tmpBkReader2!=null) {
                                        String respCode2 = tmpBkReader2.getFirstText("/Message/Head/ReturnCode");
                                        String respInfo2 = tmpBkReader2.getFirstText("/Message/Head/ReturnMsg");
                                        if ("000000".equals(respCode2)) {//交易成功
                                            note = tmpBkReader2.getFirstText("/Message/Body/Map/Remark").trim();
                                        }else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = respInfo2;
                                            break;
                                        }
                                    }else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "查询明细详情异常";
                                        break;
                                    }
                                }else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "查询明细详情异常";
                                    break;
                                }*/
                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                detail.tranDate =DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("JnlDate").trim());
                                detail.valueDate = detail.tranDate;
                                detail.actNum = p_req7516.actNum;
                                detail.tranTime = detail.valueDate+ " " + readXElement.getSingleTextNotNull("JnlTime").trim();
                                detail.comment = "";
                                String note = readXElement.getSingleTextNotNull("TransInfo").trim();
                                detail.abstr = pickupAbstr(note);
                                detail.usage = note;
                                detail.askNumber = readXElement.getSingleTextNotNull("JnlNo").trim();
                                detail.recAccNum = readXElement.getSingleTextNotNull("PayeeAcNo").trim();
                                detail.recAccName = readXElement.getSingleTextNotNull("PayeeAcName").trim();
                                detail.recAccBank = readXElement.getSingleTextNotNull("PayeeBankName").trim();
                                detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("Currency").trim());//币种
                                detail.accBal = readXElement.getSingleTextNotNull("Balance").trim();//账户余额
                                detail.tranAmt = readXElement.getSingleTextNotNull("Amount").trim();//交易金额
                                String cdFlag = readXElement.getSingleTextNotNull("DCFlag").trim();//借贷标识
                                if (cdFlag.equals("C")) {
                                    if(detail.tranAmt.indexOf("-")>=0) {
                                        detail.cdFlag = "1";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    }else{
                                        detail.cdFlag = "2";
                                    }
                                } else if(cdFlag.equals("D")) {
                                    if(detail.tranAmt.indexOf("-")>=0){
                                        detail.cdFlag = "2";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    }else{
                                        detail.cdFlag = "1";
                                    }
                                }else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "借贷标志( " + cdFlag + ")无法识别，请与银行核对";
                                    break;
                                }
                                retAtsTrans.writeRetDetail(detail);
                            }
                            if("-1".equals(tmpRespCode)){
                                break;
                            }
                        }else{
                            tmpRespCode = "-1";
                            tmpRespInfo = respInfo;
                            break;
                        }
                    }else{
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }

                }else{
                    tmpRespCode = "-1";
                    tmpRespInfo = resutlt[1];
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
